﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Music_Organizer
{
    class FileManager
    {
        public FileManager()
        {

        }

        public bool CopyFile(string copyPath, string pastePath)
        {
            bool success = false; //Result

            //Clean paste path for illegal characters
            string pastePathRoot = System.IO.Path.GetPathRoot(pastePath);
            string pastePathDirectory = System.IO.Path.GetDirectoryName(pastePath).Replace(pastePathRoot,"");
            string pastePathFile = System.IO.Path.GetFileName(pastePath);
            string invalid = new string(System.IO.Path.GetInvalidPathChars()) + ":";
            foreach (char c in invalid)
            {
                pastePathDirectory = pastePathDirectory.Replace(c.ToString(), "");
            }
            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                pastePathFile = pastePathFile.Replace(c.ToString(), "");
            }
            pastePath = pastePathRoot + pastePathDirectory + "\\" + pastePathFile;

            //Try to create the folder
            bool pasteFolderExsists = CreateFolder(System.IO.Path.GetDirectoryName(pastePath));

            if (pasteFolderExsists)
            {
                try
                {
                    if (!System.IO.File.Exists(pastePath))//Make sure the file isn't already there
                    {
                        System.IO.File.Copy(copyPath, pastePath);
                        success = true;
                    }
                    else
                    {
                        //System.Windows.Forms.MessageBox.Show(pastePath + " already exsists");
                    }
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Error copying " + copyPath);
                }
            }

            return success;
        }

        private bool CreateFolder(string root, string subfolder) //Creates folders if folder doesn't exsist
        {
            //Create a new subfolder under the current active folder
            string newPath = System.IO.Path.Combine(root, subfolder);

            return CreateFolder(newPath);
        }
        private bool CreateFolder(string path)
        {
            try
            {
                if (!System.IO.Directory.Exists(path))  //Check if subfolder exsists
                {
                    System.IO.Directory.CreateDirectory(path);  //Create the subfolder
                }
                return true;
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Unable to create " + path);
                return false;
            }
        }
    }
}
